package com.yfyszk.kingbird.config;


import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.yfyszk.kingbird.common.exception.BizCodeEnum;
import com.yfyszk.kingbird.common.exception.ResultEnum;
import com.yfyszk.kingbird.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: Sentinel 限流
 * @author: wgc
 * @createTime: 2020-07-13 11:30
 **/

@Configuration
public class UserSentinelConfig {

    public UserSentinelConfig() {
//网关限流了请求，就会调用此回调
        WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
            @Override
            public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
                R error = R.error(ResultEnum.TO_MANY_REQUEST.getCode(), ResultEnum.TO_MANY_REQUEST.getMsg());
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json");
                response.getWriter().write(JSON.toJSONString(error));

            }
        });

    }

}

